package com.example.cinemasystemv2.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        Object message = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        
        if (status != null) {
            Integer statusCode = Integer.valueOf(status.toString());
            model.addAttribute("statusCode", statusCode);
            
            switch (statusCode) {
                case 404:
                    model.addAttribute("errorTitle", "页面未找到");
                    model.addAttribute("errorMessage", "抱歉，您访问的页面不存在。");
                    break;
                case 403:
                    model.addAttribute("errorTitle", "访问被拒绝");
                    model.addAttribute("errorMessage", "您没有权限访问此页面。");
                    break;
                case 500:
                    model.addAttribute("errorTitle", "服务器内部错误");
                    model.addAttribute("errorMessage", "服务器遇到了一个错误，请稍后再试。");
                    break;
                default:
                    model.addAttribute("errorTitle", "发生错误");
                    model.addAttribute("errorMessage", "系统遇到了一个未知错误。");
                    break;
            }
        } else {
            model.addAttribute("statusCode", 500);
            model.addAttribute("errorTitle", "发生错误");
            model.addAttribute("errorMessage", "系统遇到了一个未知错误。");
        }
        
        if (message != null) {
            model.addAttribute("detailMessage", message.toString());
        }
        
        return "error";
    }
}